<template>
  <div class="app-container app-view-box">
    <el-alert size="mini" show-icon class="mg-b5" type="warning" title="1.更新时间：一般在老师发布答案后半个小时内更新。" />
    <el-alert size="mini" show-icon class="mg-b5" type="warning" title="2.第一次更新后，后续作答的同学，可以在次日上午看到自己的统计数据。" />
    <el-alert size="mini" show-icon class="mg-b5" type="warning" title="3.每次查看，若发现数据不是最新的，电脑端建议采用 ctrl+f5 快捷键刷新页面，手机端微信打开，建议清除微信缓存或者改用手机其他浏览器打开。" />

    <div class="line pd-b20 flex flex-l">
      <label for="">答题日期：</label>
      <el-select v-model="examDate" size="mini" placeholder="请选择" @change="selectChange">
        <el-option v-for="item in dateList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button icon="el-icon-refresh" type="primary" class="mg-l5" size="mini" @click="refreshFn">
        刷新
      </el-button>
      <!-- <el-button icon="el-icon-refresh" :type="startDynamic ? 'danger' : 'primary'" class="mg-l5" size="mini" @click="dynamic">
        {{startDynamic ? '暂停演示' : '动态演示'}}
      </el-button> -->
    </div>

    <div class="board-box clearfix">
      <div class="sider-r fl">
        <div class="top-box clearfix">
          <div class="sider-box sider-box1 fl">
            <div class="line-tit">
              考试日期：{{ examDateStr }}
            </div>
            <span class="tit-txt txt1">距离考试时间，还剩：</span>
            <div class="days clearfix">
              {{ countdownDays }}
              <span class="txt2">天</span>
            </div>
          </div>

          <div class="sider-box sider-box0 fr">
            <div class="tit-txt">
              本次答题及格率：{{ rightRate }}%
            </div>
            <div id="pieChartDom" class="echart-cls1"></div>
          </div>
        </div>
        <!-- 统计图 -->
        <div class="echart-box">
          <div id="lineChartDom" class="echart-cls"></div>
        </div>
      </div>

      <div class="common-table no-edit-table fr">
        <el-table v-loading="tableLoading" :border="true" :data="tableData" class="common-table-box" style="width: 100%" height="700" stripe :header-row-style="{height: '40px'}" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" highlight-current-row @sort-change="sortChange">
          <el-table-column label="行号" type="index" align="center" width="50" />
          <el-table-column v-for="item of columns" :key="item.colName" :prop="item.colName" :label="item.label" :width="item.width" :min-width="item.minWidth" :align="item.align || 'left'" :fixed="item.fixed" :sortable="item.sortable">
            <template slot-scope="scope">
              <!-- <CellItem :group-item="colItem" :row="scope.row" @formEvent="formEvent" /> -->
              <div v-if="item.isHtml" :class="item.class" class="flex flex-l" v-html="scope.row[item.colName]"></div>
              <!-- isLink:1.链接，点击支持跳转 -->
              <span v-else-if="item.isOpration" :class="item.class" :style="item.style" :data-islink="item.link ? 1 : 0">
                <el-button size="mini" class="fs-12 pd-5" @click="jumpToDetail(scope.row)">查看分析</el-button>
              </span>
              <span v-else :class="item.class" :style="item.style" :data-islink="item.link ? 1 : 0">{{ scope.row[item.colName] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>

// 引入 ECharts 主模块
var echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/line')
// 引入柱状图
require('echarts/lib/chart/bar')
require('echarts/lib/chart/pie')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')

export default {
  name: 'Statistics',
  data () {
    return {
      startDynamic: null,
      examDateStr: '2022.11.27',
      countdownDays: 0,
      rightRate: 0,
      tableLoading: false,
      dateList: [],
      examDate: '',
      columns: [
        { label: '姓名', colName: 'stuName', width: 80, isHtml: false, fixed: false },
        { label: '总平均分', colName: 'avg', width: 100, align: '', isHtml: false, sortable: true },
        { label: '答题次数', colName: 'stuExamNum', width: 80, align: 'center', isHtml: false },
        { label: '本次正确率', colName: 'score', width: 90, align: 'center', isHtml: false },
        { label: '本次答案', colName: 'scoreHtml', width: 'auto', minWidth: 200, isHtml: true },
        { label: '分析&建议', colName: 'analysis', width: 85, isHtml: false, isOpration: true, fixed: 'right' }
      ],
      tableData: []
    }
  },
  created () {
    this._numObj = {}
  },
  mounted () {
    this.dateList = window.dateList || this.$constant.dateList
    // debugger
    this.$com.getStaticData(() => {
      console.log('$constant: ', this.$constant)
      // console.log('loadAllData: ', this.$constant.loadAllData)
      // console.log('countAllData: ', this.$constant.countAllData)
      // console.log('userOtherInfo: ', this.$constant.userOtherInfo)
      // console.log('charpterExamNum: ', this.$constant.charpterExamNum)
      // console.log('chapterAnswerData: ', this.$constant.chapterAnswerData)
      // console.log('rightAswerObj: ', this.$constant.rightAswerObj)
      // console.log('subjectData: ', this.$constant.subjectData)
      // console.log('analysisUserData: ', this.$constant.analysisUserData)
      // console.log('subjectAllList: ', this.$constant.subjectAllList)

      this.initFn()

      // debugger
      this.$nextTick(() => {
        this.resizeFn() // 窗口宽度变化触发
      })
    })
    this.initExamDate()
  },
  methods: {
    // 动态演示
    dynamic () {
      if (!this.startDynamic) {
        this.timeExecut()
        this.startDynamic = setInterval(() => {
          this.timeExecut()
        }, 2000)
      } else {
        clearInterval(this.startDynamic)
        this.startDynamic = null
      }

      // refreshFn
    },
    timeExecut () {
      const _this = this
      const maxLen = _this.dateList.length - 1
      _this.dateList.some((o, i) => {
        if (_this.examDate === o.value) {
          const num = i + 1
          // debugger
          if (num > maxLen) {
            _this.examDate = _this.dateList[0].value
          } else {
            _this.examDate = _this.dateList[num].value
          }
          return true
        }
      })

      _this.selectChange(_this.examDate)
    },
    // change event select
    selectChange (value) {
      this.tableLoading = true
      this.examDate = value
      this.$common.setHrefParams({ date: this.examDate })
      // debugger
      // 递归等待异步加载的js数据（动态引入js数据有延迟）
      this.getCurDateTableData((rData) => {
        this.tableData = rData.tableData
        // debugger
        this._originTableData = this.$common.deepCloneObj(rData.tableData)
        // debugger
        const { echartDom } = this.$echartCom.initLineEchart({ echarts, domId: 'lineChartDom', countData: this.$constant.countAllData[this.curDate], curDate: this.examDate })

        this.initPieData()
        // debugger

        this.lineEchartDom = echartDom
        this.tableLoading = false
      })
    },
    // 计算考试倒计时
    initExamDate () {
      this.examDateStr
      const curDate = this.$processDate.turnDate()
      const examDate = this.$processDate.turnDate(this.examDateStr)
      const distamp = examDate.timeStamp - curDate.timeStamp
      let surplusDay = 0
      if (distamp > 0) {
        surplusDay = parseInt(distamp / 24 / 60 / 60 / 1000)
      }
      // debugger
      this.countdownDays = surplusDay
      // countdownDays
    },
    refreshFn () {
      window.location.reload()
    },
    // 按总平均分排序
    sortChange ({ column, order, prop }) {
      if (order) {
        let num = 1
        if (order === 'descending') { // 下降
          num = -1
        }
        console.log('order', order, num)
        // debugger
        this.tableData.sort((a, b) => (a.avg - b.avg) * num)
      } else {
        // debugger
        this.tableData = this._originTableData
      }
      // this.$com.tableSortFn(prop, this.examDate)
    },
    // 窗口宽度变化触发
    resizeFn () {
      // echarts 响应 加上函数节流
      window.addEventListener('resize', this.$common.throttle(() => {
        this.lineEchartDom && this.lineEchartDom.resize() // 柱状图
        this.pieEchartDom && this.pieEchartDom.resize() // 饼图
      }))
    },
    getHtml (item, row) {
      const t = row[item.colName]
      return t
    },
    getTdValue (item, row) {
      const t = row[item.colName]
      return t
    },
    initFn () {
      const queryParams = this.$common.getCurPathParam()
      // debugger
      this.examDate = ''
      if (queryParams && queryParams.hasOwnProperty('date') && !this.$validate.isNull(queryParams.date)) {
        this.dateList.some(o => {
          if (o.value === queryParams.date) {
            this.examDate = queryParams.date
            return true
          }
        })
      }

      if (this.$validate.isNull(this.examDate)) { // 为空，则采用最后一个答题日期
        const lastLen = this.dateList.length - 1
        this.examDate = this.dateList[lastLen].value
      }

      this.selectChange(this.examDate)
    },
    // 跳转分析
    jumpToDetail (row) {
      const query = {
        stuName: row.stuName,
        date: row.date,
        // stuExamNum: row.stuExamNum
      }

      this.$router.push({ name: 'AnalysisPresoner', query })
      // const urlStr = this.$common.obj2Str(query)
      // const url = `/#/analysis-presoner${urlStr}`
      // window.open(url)
    },
    initPieData () {
      // 初始化饼图
      const pieData = [
        { value: 0, name: '及格人数' },
        { value: 0, name: '不及格人数' }
      ]
      this.tableData.forEach(o => {
        const num = parseInt(o.score)
        if (num >= 60) {
          pieData[0].value++
        } else {
          pieData[1].value++
        }
      })
      // debugger
      // pieData[0].name = '及格人数' + this.calcularPie(pieData[0].value, this.tableData.length)
      // pieData[1].name = '及格人数' + this.calcularPie(pieData[1].value, this.tableData.length)
      this.rightRate = this.calcularPie(pieData[0].value, this.tableData.length)
      const { echartDom } = this.$echartCom.initPieEchart({ echarts, domId: 'pieChartDom', data: pieData, countData: this.$constant.countAllData[this.curDate], curDate: this.examDate })
      this.pieEchartDom = echartDom
    },
    calcularPie (num, count) {
      let val = num / count * 10000
      // debugger
      val = parseInt(val)
      val = val / 100
      return val
    },
    // 递归等待异步加载的js数据（动态引入js数据有延迟）
    getCurDateTableData (fn) {
      setTimeout(() => {
        if (!this._numObj[this.examDate]) {
          this._numObj[this.examDate] = 0
        }
        this._numObj[this.examDate]++
        console.log('getCurDateTableData1---date:', this.examDate, this._numObj)
        if (this._numObj[this.examDate] === 10) { // 超过10次重新刷新
          window.location.reload()
        }
        const rData = this.$constant.loadAllData[this.examDate]
        if (this.$validate.isNull(rData)) {
          this.getCurDateTableData(fn)
        } else {
          fn(rData)
        }
      }, 300)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-view-box {
  $tableW: 60%;
  $rightW: 100% - $tableW - 1%;
  // background: url(../../assets/images/bg.jpg);
  // .line label {
  //   color: #fff;
  // }
  .board-box {
    padding: 10px;
    width: 100%;
    border: 1px solid #eee;
  }
  .common-table {
    width: $tableW;
  }

  .sider-r {
    $slicerH: 700px;
    $sliderTopH: 150px;
    $slicerBottomH: $slicerH - $sliderTopH;
    width: $rightW;
    height: $slicerH;
    .top-box {
      width: 100%;
      height: $sliderTopH;
      // border: 1px solid #eee;
      .sider-box {
        padding: 10px;
        width: 49%;
        height: $sliderTopH;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .tit-txt {
          font-size: 14px;
          line-height: 30px;
        }
      }
      .sider-box0 {
        .echart-cls1 {
          width: 100%;
          height: $sliderTopH - 30px - 20px;
          // background: pink;
        }
      }
      .sider-box1 {
        padding: 10px;
        font-size: 14px;
        .line-txt {
          line-height: 30px;
        }
        .line-tit {
          line-height: 20px;
        }
        .days {
          position: relative;
          padding: 10px 0;
          text-align: center;
          font-size: 60px;
          font-weight: bold;
        }
        .txt2 {
          // position: relative;
          // bottom: 0;
          // right: 0;
          line-height: 30px;
          font-size: 14px;
          font-weight: normal;
          vertical-align: bottom;
        }
      }
    }
    .echart-box {
      margin: 10px 0;
      width: 100%;
      height: $slicerBottomH;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      .echart-cls {
        border: none;
      }
    }
  }
}

@media screen and (max-width: 780px) {
  .app-view-box {
    $tableW1: 100%;
    $rightW1: 100%;
    .board-box {
      padding: 10px;
      width: 100%;
      border: 1px solid #eee;
    }
    .common-table {
      margin: 30px 0;
      width: $tableW1;
    }

    .sider-r {
      width: $rightW1;
      height: 700px;
      // .echart-box {
      // }
    }
  }
}
</style>
